package v1

import (
	"card/app/http/controllers/api"
	"card/app/logic"
	"card/app/requests"
	"card/pkg/jwt"
	"card/pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

type LoginController struct {
	api.BaseApiController
}

func (ctrl *LoginController) Login(c *gin.Context) {
	params := new(requests.LoginRequest)
	if err := requests.Validate(c, params, requests.LoginValidate); err != nil {
		response.Error(c, err)
		return
	}
	memberLogic := logic.NewMember(c)
	userId, err := memberLogic.Login(params)
	if err != nil {
		response.Error(c, err, err.Error())
		return
	} else {
		token, err := jwt.NewJwt().IssueToken(cast.ToString(userId))
		if err != nil {
			response.Error(c, err)
			return
		} else {
			response.Data(c, map[string]interface{}{
				"token": token,
			}, "登陆成功")
		}
	}
}

// 用token换取access_token
func (ctrl *LoginController) RefreshToken(c *gin.Context) {
	token, err := jwt.NewJwt().RefreshToken(c)
	if err != nil {
		response.Error(c, err, "令牌刷新失败")
	} else {
		response.JSON(c, gin.H{
			"token": token,
		})
	}
}
